package com.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DbUtil {
	/**
	 * Connection
	 * 
	 * config.urlPattern + "//" + config.databasePath + "/" +
	 * config.databaseName
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		Config config = new Config();

		Connection conn = null;// "jdbc:mysql://127.0.0.1/
		try {
			Class.forName(config.driverName);

			String url = config.urlPattern + "//" + config.databasePath + ":"
					+ config.portNumber + "/" + config.databaseName;
			url += "?useUnicode=true&characterEncoding=UTF-8";
			
			Log.write(url);
			
			String userName =  config.userName;
			String password = config.password;
			
			conn = DriverManager.getConnection(url,userName,password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(Statement pstmt) {
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void close(Statement pstmt,ResultSet rs,Connection conn) {
		try {
			if(pstmt!=null)  pstmt.close();
			if(rs!=null)  rs.close();
			if(conn!=null)  conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void beginTransaction(Connection conn) {
		try {
			if (conn != null) {
				if (conn.getAutoCommit()) {
					conn.setAutoCommit(false); 
				}
			}
		} catch (SQLException e) {
		}
	}

	public static void commitTransaction(Connection conn) {
		try {
			if (conn != null) {
				if (!conn.getAutoCommit()) {
					conn.commit();
				}
			}
		} catch (SQLException e) {
		}
	}

	public static void rollbackTransaction(Connection conn) {
		try {
			if (conn != null) {
				if (!conn.getAutoCommit()) {
					conn.rollback();
				}
			}
		} catch (SQLException e) {
		}
	}

	public static void resetConnection(Connection conn) {
		try {
			if (conn != null) {
				if (conn.getAutoCommit()) {
					conn.setAutoCommit(false);
				} else {
					conn.setAutoCommit(true);
				}
			}
		} catch (SQLException e) {
		}
	}

}
